package com.xiaoyu.binaryTree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @program: DS_and_A
 * @description: TODO
 * @author: YuWenYi
 * @create: 2021-05-20 15:00
 **/
public class Inorder_94 {
    static List<Integer> res = new ArrayList<>();
    public static List<Integer> inorderTraversal(TreeNode root) {
        if (root == null){
            return new ArrayList<>();
        }
        if (root.left != null){
            inorderTraversal(root.left);
        }
        res.add(root.val);
        if (root.right != null){
            inorderTraversal(root.right);
        }
        return res;
    }

    //官方递归
    public List<Integer> inorderTraversal1(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        inorder(root, res);
        return res;
    }

    public void inorder(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        inorder(root.left, res);
        res.add(root.val);
        inorder(root.right, res);
    }


    //非递归算法,迭代 --> 显式的使用栈--> 官方题解
    public static List<Integer> inorderTraversal2(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        LinkedList<TreeNode> stack = new LinkedList<>();

        while (root!=null || !stack.isEmpty()){
             while (root != null){
                 stack.push(root);
                 root = root.left;
             }
             root = stack.pop();
             res.add(root.val);
             root = root.right;
        }
        return res;
    }

    //与前序后续配套的使用if和else
    public static List<Integer> inorderTraversal3(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        LinkedList<TreeNode> stack = new LinkedList<>();
        //触底后再去添加元素
        while (root!=null || !stack.isEmpty()){
            if (root != null){
                stack.push(root);
                root = root.left;
            }else {
                root = stack.pop();
                res.add(root.val);
                root = root.right;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        ArrSortedArrayToBST_108 sb = new ArrSortedArrayToBST_108();
        TreeNode right = new TreeNode(3,new TreeNode(6),new TreeNode(7));
        TreeNode left = new TreeNode(2,new TreeNode(4),new TreeNode(5));
        TreeNode root = new TreeNode(1,left,right);
        System.out.println(inorderTraversal3(root));
    }
}
